<script setup lang="ts">
  import { addPatientApi, patientDetailApi, updatePatientApi } from '@/apis/patient'
  import type { PatientItem } from '@/types/patient'
  import { onLoad } from '@dcloudio/uni-app'
  import { ref } from 'vue'

  // 1. 表单数据
  const formData = ref({
    /** 患者姓名 */
    name: '',
    /** 患者身份证号 */
    idCard: '',
    /** 性别，1：男，0：女 */
    gender: 1,
    /** 是否设置为默认患者 1：是，0：否 */
    defaultFlag: 1,
  })

  // 是否为默认就诊人
  const onSwitchChange = (event: UniHelper.SwitchOnChangeEvent) => {
    // switch 组件收集的是 boolean 类型，后端要求的是数字 0 或 1
    formData.value.defaultFlag = event.detail.value ? 1 : 0
  }

  // 创建一个对表单实例的引用，用于后续操作和管理表单状态
  const formRef = ref<UniHelper.UniFormsInstance>()
  // 表单校验规则
  const formRules: UniHelper.UniFormsRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请输入患者姓名' },
        { pattern: /^[\u4e00-\u9fa5]{2,7}$/, errorMessage: '请输入正确的姓名' },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请输入患者身份证号' },
        {
          pattern:
            /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))((0[1-9])|([12][0-9])|(3[01]))\d{3}(\d|X|x)$/,
          errorMessage: '请输入正确的身份证号',
        },
      ],
    },
    //
    gender: {
      rules: [
        { required: true, errorMessage: '请选择性别' },
        {
          // 自定义校验规则
          validateFunction: (rule, value, data, callback) => {
            // console.log('自定义校验规则', rule, value, data, callback)
            if (Number(formData.value.idCard.charAt(16)) % 2 !== value) {
              callback('身份证号与性别不匹配')
            }
            return true
          },
        },
      ],
    },
  }

  // 提交表单
  const onSubmit = async () => {
    try {
      // 表单校验
      await formRef.value?.validate?.()
      // 判断是否有 id
      if (routerParams.id) {
        // 修改患者信息
        await updatePatientApi({
          ...formData.value,
          id: routerParams.id,
        })
      } else {
        // 提交表单给服务器，添加患者信息
        await addPatientApi(formData.value)
      }
      uni.showToast({ title: '保存成功', icon: 'success' })
      // 返回上一页
      uni.navigateBack()
    } catch (error) {
      console.log(error)
    }
  }

  // defineProps
  //    页面 - 获取页面参数
  //    组件 - 获取父传子的参数
  const routerParams = defineProps<{ id?: string }>()
  // console.log(routerParams)

  // 根据 id 获取患者详情
  const getDetail = async (id: string) => {
    // 获取患者详情数据
    const res = await patientDetailApi(id)
    // console.log(res)
    formData.value.name = res.name
    formData.value.idCard = res.idCard
    formData.value.gender = res.gender || 0
    formData.value.defaultFlag = res.defaultFlag
  }

  if (routerParams.id) {
    uni.setNavigationBarTitle({ title: '编辑患者信息' })
    getDetail(routerParams.id)
  }
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="formRef" :rules="formRules" v-model="formData">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
            v-model="formData.name"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
            v-model="formData.idCard"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
            v-model="formData.gender"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch
              @change="onSwitchChange"
              :checked="formData.defaultFlag === 1"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <button @click="onSubmit()" class="uni-button">保存</button>
      </uni-forms>
    </view>
  </scroll-view>
  <text>{{ formData }}</text>
</template>

<style lang="scss">
  @import './index.scss';
</style>
